﻿namespace Gmantis.Controls.DataGrid
{
    internal class DataGridNewRowManager
    {
        // Fields
        private DataGridModel _model;
        private DataGridNewRow _newRow;

        // Methods
        public DataGridNewRowManager(DataGridModel model)
        {
            this._model = model;
        }

        public void UpdateNewRowVisibility()
        {
            if (this.ShowNewRow)
            {
                if (this.DataGrid.NewRowVisibility != DataGridNewRowVisibility.Top)
                {
                    if (this.Model.Rows.TopRows.Contains(this.NewRow))
                    {
                        this.Model.Rows.TopRows.Remove(this.NewRow);
                    }
                    if (!this.Model.Rows.BottomRows.Contains(this.NewRow))
                    {
                        this.Model.Rows.BottomRows.Insert(0, this.NewRow);
                    }
                }
                else
                {
                    if (this.Model.Rows.BottomRows.Contains(this.NewRow))
                    {
                        this.Model.Rows.BottomRows.Remove(this.NewRow);
                    }
                    if (!this.Model.Rows.TopRows.Contains(this.NewRow))
                    {
                        this.Model.Rows.TopRows.Add(this.NewRow);
                    }
                }
            }
            else
            {
                if (this.Model.Rows.TopRows.Contains(this.NewRow))
                {
                    this.Model.Rows.TopRows.Remove(this.NewRow);
                }
                if (this.Model.Rows.BottomRows.Contains(this.NewRow))
                {
                    this.Model.Rows.BottomRows.Remove(this.NewRow);
                }
            }
        }

        // Properties
        public DataGrid DataGrid
        {
            get
            {
                return this.Model.DataGrid;
            }
        }

        private DataGridModel Model
        {
            get
            {
                return this._model;
            }
        }

        public DataGridNewRow NewRow
        {
            get
            {
                if ((this._newRow == null) && this.ShowNewRow)
                {
                    this._newRow = (DataGridNewRow)this.Model.CreateRow(DataGridRowType.New, null);
                    this._newRow.Type = DataGridRowType.New;
                }
                return this._newRow;
            }
        }

        public bool ShowNewRow
        {
            get
            {
                return ((this.Model.DataGrid.IsAddingNewRowsAllowed && this.Model.DataGrid.CanUserAddRows) && (this.Model.GroupManager.GroupCount == 0));
            }
        }
    }
}
